<!-- 添加用户 -->
<template>
  <el-dialog :visible.sync="dialogVisible" :before-close="handleCloseBindWarnStandard" :close-on-click-modal="false" :title="title" width="500px" height="300px">
    <el-form v-loading="formLoading" ref="dialogForm" :model="dialogForm" :rules="rules" label-width="120px">
      <div v-if="dialogType=='添加'">
        <el-form-item v-if="addType=='单个添加'" label="添加方式">
          <el-button type="primary" @click="addTypeSwitch('单个添加')">单个添加</el-button>
          <el-button type="" @click="addTypeSwitch('批量导入')">批量导入</el-button>
        </el-form-item>
        <el-form-item v-else label="添加方式">
          <el-button type="" @click="addTypeSwitch('单个添加')">单个添加</el-button>
          <el-button type="primary" @click="addTypeSwitch('批量导入')">批量导入</el-button>
        </el-form-item>
      </div>
      <el-form-item label="所属单位" prop="corp_id">
        <el-select v-if="dialogType=='添加'" v-model="dialogForm.corp_id" clearable filterable allow-create default-first-option autocomplete="off" placeholder="请输入单位名称">
          <el-option v-for="item in companyList" :key="item.corp_id" :label="item.name" :value="item.corp_id" />
        </el-select>
        <el-input v-else v-model="dialogForm.corp_name" class="el-disabled" readonly="readonly"/>
      </el-form-item>
      <el-form-item v-if="addType=='单个添加'" label="姓名" prop="nickname">
        <el-input v-model="dialogForm.nickname" placeholder="请输入姓名" autocomplete="off"/>
      </el-form-item>
      <el-form-item v-if="addType=='单个添加'" label="手机号码" prop="mobile">
        <el-input v-if="dialogType=='添加'" v-model="dialogForm.mobile" placeholder="请输入手机号码" autocomplete="off"/>
        <el-input v-else v-model="dialogForm.mobile" class="el-disabled" readonly="readonly"/>
      </el-form-item>
      <el-form-item v-if="addType=='单个添加'" label="角色" prop="role">
        <el-select v-if="dialogType=='添加'" v-model="dialogForm.role" placeholder="请选择角色">
          <el-option v-for="value in roleList" :key="value" :label="value" :value="value" />
        </el-select>
        <el-input v-else v-model="dialogForm.role" class="el-disabled" readonly="readonly"/>
      </el-form-item>
      <el-form-item v-if="addType=='批量导入'" label="用户信息表" prop="file" class="isButton">
        <el-input placeholder="请上传用户信息表" autocomplete="off"/>
        <el-button type="primary" @click="downloadTemplate">下载模板</el-button>
        <input id="upload" name="excelFile" class="hide" type="file" @change="upload">
        <i class="el-icon-upload2 el-input-icon" style="cursor: pointer;" @click="importUser"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import $ from 'jquery'
import { getSocialUnit } from '@/api/company'
import { userRoleList } from '@/api/common'
import { usersAdd, usersUpdate, usersExport } from '@/api/users'
import { validateMobile } from '@/utils/validate'
const isMobile = (rule, value, callback) => {
  if (!validateMobile(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    dialogForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dialogType: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data() {
    return {
      title: '',
      requestFn: {},
      companyList: [],
      addType: '单个添加',
      roleList: [],
      mobileRequired: true,
      subordinateUnit: '上海励尔信息科技有限公司/本单位',
      // 添加form验证
      rules: {
        nickname: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        corp_id: [{
          required: true,
          message: '请选择所属单位',
          trigger: 'blur'
        }],
        mobile: [{
          required: true,
          message: '请输入手机号码',
          trigger: 'blur'
        },
        {
          validator: isMobile,
          trigger: 'blur'
        }],
        role: [{
          required: true,
          message: '请选择角色',
          trigger: 'blur'
        }]
      },
      formLoading: false
    }
  },
  watch: {
    dialogType(val) {
      if (val === '添加') {
        this.title = '添加用户'
        this.requestFn = usersAdd
        this.mobileRequired = true
      } else if (val === '修改') {
        this.title = '修改用户'
        this.requestFn = usersUpdate
        this.mobileRequired = false
      }
      this.getUserRole()
      this.getSocialUnit()
    },
    dialogForm(val) {
      this.dialogForm = val
    }
  },
  created() {
    if (this.dialogType === '添加') {
      this.title = '添加用户'
      this.requestFn = usersAdd
    }
    if (this.dialogType === '修改') {
      this.title = '修改用户'
      this.requestFn = usersUpdate
    }
    this.getUserRole()
    this.getSocialUnit()
  },
  methods: {
    submitForm(val) {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          const that = this
          that.formLoading = true
          var params = {}
          if (this.dialogType === '添加') {
            params = {
              uuid: that.dialogForm.uuid,
              nickname: that.dialogForm.nickname,
              mobile: that.dialogForm.mobile,
              role: that.dialogForm.role,
              corp_id: that.dialogForm.corp_id
            }
          }
          if (this.dialogType === '修改') {
            params = {
              uuid: that.dialogForm.uuid,
              nickname: that.dialogForm.nickname
            }
          }
          that.requestFn(params)
            .then((res) => {
              const data = res.data
              if (data.code === 40000) {
                that.$message.success(data.message)
                that.$emit('submitForm', that.dialogForm)
                that.formLoading = false
              } else {
                that.$message.warning(data.message)
                that.formLoading = false
              }
            })
            .catch((err) => {
              console.log(err)
              that.formLoading = false
            })
        }
      })
    },
    // 新增用户方式切换
    addTypeSwitch(data) {
      this.addType = data
    },
    // 下载模板
    downloadTemplate() {
      var $form = $('<form method="GET"></form>')
      $form.attr('action', '/static/excels/userTemplate.xlsx')
      $form.appendTo($('body'))
      $form.submit()
    },
    // 导入用户
    importUser() {
      if (this.dialogForm.corp_id !== '') {
        $('#upload').click()
      } else {
        this.$message.warning('请选择所属单位！')
      }
    },
    upload(e) {
      var file = e.target.files[0]
      const isImage = file.name.substr(file.name.length - 4) === 'xlsx'
      const that = this
      if (!isImage) {
        that.$message.warning('导入文件只能是 xlsx 格式!')
        return false
      }
      const image = new window.FormData()
      image.append('excelFile', file)
      image.append('corp_id', that.dialogForm.corp_id)
      if (!that.dialogForm.corp_id) {
        return false
      }
      var params = {
        fileType: 'file',
        data: image
      }
      that.formLoading = true
      usersExport(params)
        .then((res) => {
          const data = res.data
          that.formLoading = false
          if (data.code === 40000) {
            that.$message.success(data.message)
            that.$emit('submitForm', that.dialogForm)
          } else {
            that.$message.warning(data.message)
          }
        })
        .catch((err) => {
          console.log(err)
          that.formLoading = false
        })
    },
    // 关闭弹窗
    handleCancel() {
      this.$emit('getCancel')
    },
    // 关闭弹窗，不可以删这个方法。不用这个方法点击遮罩层关闭会报错
    handleCloseBindWarnStandard() {
      this.$emit('closeBindWarnStandard')
    },
    getSocialUnit() {
      const that = this
      getSocialUnit()
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            if (data.data && data.data.length > 0) {
              that.companyList = data.data
            }
          }
        })
        .catch(() => {
        })
    },
    // 获取用户角色
    getUserRole() {
      const that = this
      userRoleList()
        .then(response => {
          if (response.data.code === 40000) {
            that.roleList = response.data.data
          } else {
            that.$message.warning(response.data.message)
          }
        })
        .catch(() => {
        })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.el-icon-upload2{
    color: #409eff;
    font-size: 16px;
}
#upload{
  display: none;
}
</style>
